package com.ahm.server.service.impl;

import com.ahm.server.common.RespBean;
import com.ahm.server.mapper.RoleMapper;
import com.ahm.server.pojo.Admin;
import com.ahm.server.mapper.AdminMapper;
import com.ahm.server.pojo.Role;
import com.ahm.server.service.IAdminService;
import com.ahm.server.utils.JwtTokenUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ahm
 * @since 2021-09-22
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Resource
    private AdminMapper adminMapper;

    @Resource
    private RoleMapper roleMapper;

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;


    @Override
    public IPage<Admin> selectAdminPage(Page<Admin> page) {
        return adminMapper.selectPageVo(page);
    }
    /**
    　　* @description: 参数校验-》用户ji'l
    　　* @param ${tags}
    　　* @return ${return_type}
    　　* @throws
    　　* @author anhaimeng
    　　* @date 2021/9/23 11:24
    　　*/
    @Override
    public RespBean login(String username, String password,String Code,HttpServletRequest request) {
        System.out.println("验证码："+request.getSession().getAttribute("code"));
//         验证码进行校验
        if (StringUtils.isBlank(Code)){
            return RespBean.error("验证码不能为空");
        }
        if (!Code.equals(request.getSession().getAttribute("code"))){
            return RespBean.error("验证码错误,请刷新后重试");
        }

        request.getSession().removeAttribute("code");

        // 参数校验
        if (StringUtils.isBlank(username)){
            return RespBean.error("用户名为空");
        }
        if (StringUtils.isBlank(password)){
            return RespBean.error("密码不能为空");
        }
        // 用户记录存在查询
        UserDetails userDetails  = userDetailsService.loadUserByUsername(username);
        if (null == userDetails || !passwordEncoder.matches(password,userDetails.getPassword())){
            return RespBean.error("该用户不存在或者密码错误");
        }
        if (!userDetails.isEnabled()){
            return RespBean.error("该账号不可用请联系管理员");
        }

        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        // 放入Security环境中 ThreadLocal
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return RespBean.success("登录成功", tokenMap);


    }


}
